﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Task_Parallel_Library
{
    [TestClass]
    public class DataParallelism
    {
        [TestMethod]
        public void ParallelForEach()
        {
            //initialize
            var sourceCollection = Enumerable.Range(1, 20);
            var result = new StringBuilder();
            var random = new Random();

            //execute
            Parallel.ForEach(sourceCollection, item =>
            {
                Thread.Sleep(random.Next() % 100);
                result.Append(string.Format("{0}-", item.ToString().PadLeft(2, '0')));
            });

            //assert
            Assert.IsNotNull(result.ToString());
            Assert.AreEqual(21, result.ToString().Split('-').Length);
        }

        [TestMethod]
        public void ParallelForEach_WithBreak()
        {
            //initialize
            var breakItem = 3;
            var sourceCollection = Enumerable.Range(1, 20);
            var result = new StringBuilder();
            var random = new Random();

            //execute
            Parallel.ForEach(sourceCollection, (item, loopState) =>
            {                
                Thread.Sleep(random.Next() % 100);
                if (item == breakItem)
                {
                    loopState.Stop();
                    return;
                }
                result.Append(string.Format("{0}-", item.ToString().PadLeft(2, '0')));
            });

            //assert
            var actualResult = result.ToString().Split('-').Where(x => x != "").Select(x => Convert.ToInt32(x)).ToList();
            Assert.IsFalse(actualResult.Contains(breakItem));
            Assert.IsTrue(actualResult.Count < 20);
        }
    }
}
